/*
 * @Author: 飞越疯人院 353362604@qq.com
 * @Date: 2022-09-16 09:30:55
 * @LastEditors: 飞越疯人院 353362604@qq.com
 * @LastEditTime: 2022-09-16 15:35:01
 * @FilePath: \adminstration\src\Common\Login\CodeFunc.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { Http } from '../Api'
import { useEffect } from 'react'
import { useRequest } from 'ahooks'

const { WxLogin, location } = window

const CodeUp = ({ codeState, codeStyle, QRUuid, ProjectUuid }) => {
    const { runAsync, cancel } = useRequest(Http, {
        manual: true,
        pollingInterval: 2000,
        pollingWhenHidden: false,
        pollingErrorRetryCount: 5,
        onSuccess: ({ status, token }) => {
            if (status === '2') {
                cancel()
                sessionStorage.setItem('TOKEN', token)
                getProjectListByToKen({ url: 'getProjectListByToKen', data: { QRUuid } })
            }
        },
    })

    const { runAsync: getProjectListByToKen } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            getToKenByProjectUuid({
                url: 'getToKenByProjectUuid',
                data: { QRUuid, ProjectUuid: res.list.find(v => v.webUrl === location.hostname).uuid },
            })
        },
    })

    const { runAsync: getToKenByProjectUuid } = useRequest(Http, {
        manual: true,
        onSuccess: ({ status, token, webUrl }) => {
            const { origin } = location
            if (status === '4') {
                window.location.href = `${origin}?token=${token}`
            }
        },
    })

    useEffect(() => {
        const codeData = {
            self_redirect: true,
            id: 'QRcode',
            appid: 'wxa3d0c46c8bfcef89',
            scope: 'snsapi_login',
            redirect_uri: window.encodeURI('https://common-redirect.ljkjkf.com'),
            state: QRUuid,
            style: 'white',
            href: codeStyle,
        }
        if (codeState) {
            new WxLogin(codeData)
            runAsync({ url: 'getTokenByQRUuid', data: { QRUuid } })
        }
    }, [QRUuid, codeState, codeStyle, runAsync])
    return (
        <div className="CodeUpBox">
            <div id="QRcode" />
        </div>
    )
}
export default CodeUp
